package com.breeze.webview.webclient;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.breeze.webview.bean.JsParam;
import com.breeze.webview.callbacks.NativeToJSCallback;
import com.breeze.webview.callbacks.WebViewCallBack;
import com.google.gson.Gson;

public class BaseWebView extends WebView implements NativeToJSCallback {
    private static final String TAG = "BaseWebView";

    public BaseWebView(Context context) {
        super(context);
        init();
    }

    public BaseWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        WebViewDefaultSettings.getInstance().setSettings(this);
        // 注册了Javascript的接口后，就可以通过js中的window访问breezewebview，从而访问被@JavascriptInterface 注解过的方法
        addJavascriptInterface(this, "breezewebview");
        // 建立与主进程CommandService的链接
        WebViewProcessCommandDispatcher.getInstance().initCommandConnection();

    }

    public void registerWebViewCallback(WebViewCallBack callBack) {
        setWebViewClient(new BreezeWebViewClient(callBack));
        setWebChromeClient(new BreezeWebChromeClient(callBack));
    }

    // 被Javascript调用的方法
    @JavascriptInterface
    public void takeNativeAction(final String jsParam) {
        Log.i(TAG, "takeNativeAction: jsParam=" + jsParam);
        JsParam jsParamObj = new Gson().fromJson(jsParam, JsParam.class);
        if (jsParamObj != null) {
            WebViewProcessCommandDispatcher.getInstance().executeCommand(jsParamObj.name, new Gson().toJson(jsParamObj.param), this);
        }
    }

    @Override
    public void handleCallback(final String callbackName, final String response) {
        Log.i(TAG, "handleCallback: callbackName=" + callbackName + ", response=" + response);
        // native to js
        // 需要运行在主线程
        post(new Runnable() {
            @Override
            public void run() {
                // 调用js的breeze.callback方法，传入两个参数
                String jsCode = "javascript:breeze.callback('" + callbackName + "'," + response + ")";
                evaluateJavascript(jsCode, null);
            }
        });
    }
}
